package com.gs.synedocket.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.domain.LogData;
import com.gs.synedocket.db.dto.LogDto;
import com.gs.synedocket.presenter.LogPresenter;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.view.ILogService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LogService extends Service implements ILogService {

    private String lastIds = "";
    private static Thread thread;
    private PowerManager.WakeLock wakeLock;
    private static boolean threadDisable = true;
    private LogPresenter mPresenter;

    public static void stopLog() {
        threadDisable = false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        threadDisable = true;
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SynEDocket:CPUKeepRunning");
            wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
        }
        if (mPresenter == null) {
            mPresenter = new LogPresenter();
            mPresenter.attachView(this);
        }
        loop();
        return super.onStartCommand(intent, flags, startId);
    }

    private void loop() {
        if (thread == null) {
            thread = new Thread(() -> {
                Looper.prepare();
                while (threadDisable) {
                    try {
                        Thread.sleep(60 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (SPUtil.getInstance().getString(AllConstants.TOKEN).isEmpty()) break;
                    List<LogData> list = LogUtil.getInstance().getData(10);
                    if (list != null && !list.isEmpty()) {
                        upload(list);
                    }
                }
            });
            thread.start();
        }
    }

    private void upload(List<LogData> list) {
        try {
            StringBuilder ids = new StringBuilder();
            List<LogDto> params = new ArrayList<>();
            for (LogData bean : list) {
                ids.append(",").append(bean.getId());
                LogDto dto = new LogDto();
                dto.setLogAt(new Date(bean.getLogAt()));
                dto.setLogType(bean.getLogType());
                dto.setMessage(bean.getMessage());
                dto.setUserId(bean.getUserId());
                params.add(dto);
            }
            Log.i(AllConstants.TAG, "lastIds:" + lastIds);
            if (!lastIds.equals(ids.toString())) {
                lastIds = ids.toString();
                mPresenter.upload(params, ids.substring(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (thread != null) {
            thread = null;
        }
    }

    @Override
    public void onUploadLogSuccess(ApiResultData<String> result, String ids) {
        Log.i("uploadLocal", "nowIds:" + result.toString());
        if (result.getStatus() == 2000) {
            LogUtil.getInstance().delete(ids);
        } else {
            lastIds = "";
        }
    }

    @Override
    public void onUploadLogFails(Exception e) {
        lastIds = "";
    }
}
